<template>
  <div class="divCard">
    <el-upload
      class="uploadDom"
      action=""
      :drag="drag"
      :accept="accept"
      :disabled="disabled"
      v-model:file-list="_fileList"
      :ref="(el) => fileUpload = el"
      :http-request="fnUploadRequest"
      :before-upload="handleUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
    >
      <div class="uploadDom1">
        <div>
          <el-icon class="icon"><Tickets /></el-icon>
        </div>
        <div  class="upLoadText">
          点击或将文件拖拽到这里上传
        </div>
        <div class="upLoadText1">
          支持扩展名：.doc,.jpg,.jpeg,.png,.xls,.xlsx,.pdf
        </div>
      </div>
    </el-upload>
     <div class="div1111">
    <el-dialog
      v-model="openUp"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="60%"
    >
      <vab-pdf :source="openUp" />
    </el-dialog>
</div>
  </div>
</template>

<script lang="ts" setup>
import VabPdf from '/@/plugins/VabPdf'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {
  ElMessage,
  dayjs,
  type UploadProps,
} from 'element-plus'
import { getosssts } from '~/src/api/dms/beCurrent';
import { EstimatedTime, StrSplit } from '~/src/utils/utils';
import _ from 'lodash';
const openUp = ref<any>(undefined)
const props = defineProps({
  // 文件类型
  accept: {
    type: String,
    default: '.doc,.JPG,.JPEG,.PNG,.xls,.xlsx,.pdf',
  },
  // 限制数量
  limit: {
    type: Number,
    default: 3,
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: true
  },
  // 提示
  tip: {
    type: String,
    default: ''
  },
  fileList: {
    type: Array,
    default: () => { return [] }
  } as any,
  // 是否拖拽
  drag: {
    type: Boolean,
    default: false
  },
  // 上传文件之前的校验【限制文件大小】
  size: {
    type: Number,
    defailt: ''
  }
})

const proxy: any = getCurrentInstance()?.proxy
const fileUpload = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileName = ref('')
const todayKey = dayjs().format('YYYY-MM-DD') //当前时间2023-08-07
const folderName = 'dms'

const emit = defineEmits(['delete'])

// 数据
let _fileList = ref<any>([...props.fileList])
// 是否显示上传按钮
let isShow = ref(true)

watch(_fileList.value, (value) => {
  if (value.length < props.limit) {
    isShow.value = true
    return
  }
  isShow.value = false

})
watchEffect(() => {
  _fileList.value = [...props.fileList]
})

// 请求
const fnUploadRequest = async (options: any) => {
  const { onSuccess, onProgress, onError, file } = options
  fileName.value = file.name
  try {
    const configRes = await getosssts()
    const client = new OSS({
      region: configRes.data.regionId,
      accessKeyId: configRes.data.AccessKeyId,
      accessKeySecret: configRes.data.AccessKeySecret,
      // 从STS服务获取的安全令牌（SecurityToken）。
      stsToken: configRes.data.SecurityToken,
      // 填写Bucket名称，例如examplebucket。
      bucket: configRes.data.roleSessionName, // bucket名字
      secure: true,
    })

    const chunkSize = 1024 * 1024 * 1// 分片大小
    const chunks = Math.ceil(file.size / chunkSize) // 分片数量
    ElMessage(`预计本次上传需要${EstimatedTime(chunks)}`)
    const updateName = `${folderName}/${todayKey}/${file.name}`
    const porps: any = {
      // 获取分片上传进度、断点和返回值。
      progress: (p: any, cpt: any, res: any) => {
        onProgress({ percent: p * 100 })
        // setProgress(p * 100)
      },
      headers: {},
      parallel: chunks,
      partSize: chunkSize,
      meta: { year: dayjs().format('YYYY'), people: `${folderName}` },
      mime: 'text/plain',
    }
    client.multipartUpload(`${updateName}`, file, { ...porps }).then((res: any) => {
      let value = res.res.requestUrls[0]
      let url = value
      // 检索 是否拼 ？
      if (value.includes('?')) url = StrSplit(value, '?', 0)
      onSuccess(url)
    }).catch(function (err: any) {
      console.log(err);
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    })

  } catch (error) {
  }
}
// 上传前
const handleUpload = (file: any) => {
  const { size, type } = file

  // 是否超出限制大小
  let isExceedSize = false

  if (props.size) {
    isExceedSize = size / 1024 / 1024 > props.size

    if (isExceedSize) {
      proxy.$Message(`上传文件大小不能超过 ${props.size}MB!`, 'warning')
      return false
    }
  }

 /* if (type != 'image/jpeg' && type != 'image/png') {
    proxy.$Message(`上传文件格式不正确`, 'warning')
    return false
  }*/
}
// 预览
const handlePreview: UploadProps['onPreview'] = (uploadFile:any) => {
  if (uploadFile.response.split('.').pop() == 'pdf'){
    openUp.value = uploadFile.response
  }else {
    window.open(uploadFile.response)
  }

  //

  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  _fileList.value = uploadFiles

  if (!uploadFile.response) return
  emit('delete', uploadFile)
}
// 组件实例
defineExpose({
  list: _fileList,
})
</script>

<style lang="scss" scoped>
.default_text {
  padding-top: 12px;
}
.div1111{
  :deep(){
    .el-overlay-dialog{
      top:-100px
    }
  }
}
.divCard{
  :deep(){
  /*  .el-upload-list__item.is-success.focusing .el-icon-close-tip {
      display: none !important;
    }*/

    .el-icon--close-tip {
      display: none !important;
    }
  }
}
.none {
  :deep() {
    .el-upload--picture-card {
      display: none;
    }
  }
}

.box {
  :deep() {
    .el-upload-dragger {
      height: 100%;
      line-height: 80px;
    }
  }
}
.upLoadText{
  font-family: PingFangSC-Regular;
  font-weight: 400;
  font-size: 16px;
  color: #1D2129;
  letter-spacing: 0;
  text-align: center;
  line-height: 24px;
}
.upLoadText1{
  font-family: PingFangSC-Regular;
  font-weight: 400;
  font-size: 13px;
  color: #86909C;
  letter-spacing: 0;
  text-align: center;
  line-height: 22px;
}
.uploadDom1{
  text-align: center;

}
/*.uploadDom{
  padding: 20px;
  width: 100%;
  text-align: center;
  border-radius: 2px;
}*/
.icon{
  font-size: 30px;
  color: #1456F0;
}
</style>
